# -*- coding: utf-8 -*-
# !/usr/bin/env python
import uuid

from rest_framework.views import APIView
from components.models import SysOtherPrivilege
from components.resource_management.soft_manage.dao import query_soft_info, post_install_conf, get_install_conf, \
    update_install_conf
from components.resource_management.system_other_privilege.dao import sys_other_privilege_dict
from components.resource_management.system_other_privilege.serializers import SysOtherPrivilegeSerializer
from utils.mysql_utils import sql_encryption
from utils.views import Result

class SysOtherPrivilegeM(APIView):
    def get(self, request):
        data = request.query_params
        sys_other_privilege_dict_data = sys_other_privilege_dict(data['sys_other_privilege_flag'])
        sys_other_privilege_dict_data['sys_other_privilege_on'] = True if sys_other_privilege_dict_data.get(
            'sys_other_privilege_on') else False

        return Result.success_response(data=sys_other_privilege_dict_data, msg='查询成功')

    def post(self, request):
        data = request.data

        # if not data.get('sys_other_privilege_id'):
        #     data['sys_other_privilege_id'] = str(uuid.uuid1())
        data['sys_other_privilege_pass'] = sql_encryption(data['sys_other_privilege_pass'])

        try:
            data['sys_other_privilege_on'] = 1 if data['sys_other_privilege_on'] else 0
            save_data = SysOtherPrivilege(**data)
            save_data.save()
        except Exception as e:
            return Result.fail_response(msg=str(e))

        return Result.success_response(msg='保存成功')


    def put(self, request):
        data_dict = request.data.copy()
        data_dict['sys_other_privilege_pass'] = sql_encryption(data_dict['sys_other_privilege_pass'])
        sys_other_privilege_object = SysOtherPrivilege.objects.get(sys_other_privilege_id=data_dict['sys_other_privilege_id'])
        serializer = SysOtherPrivilegeSerializer(sys_other_privilege_object, data=data_dict)
        if serializer.is_valid():
            serializer.save()
        else:
            errors = serializer.errors.serializer.default_error_messages['invalid']
            return Result.fail_response(msg=str(errors))

        return Result.success_response(msg='修改成功')


    def delete(self, request):
        data = request.data
        sys_other_privilege_id = data['sys_other_privilege_id']

        SysOtherPrivilege.objects.filter(sys_other_privilege_id__in=sys_other_privilege_id).update(sys_other_privilege_on=0)

        return Result.success_response(msg='删除成功')